package com.ruoyi.common.h1wUtils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@Component
public class SMSUtils {
    @Value("${sms.ipyy.prefix}")
    private String ipyyPrefix;
    @Value("${sms.ipyy.url}")
    private String ipyyUrl;
    @Value("${sms.ipyy.account}")
    private String ipyyAccount;
    @Value("${sms.ipyy.password}")
    private String ipyyPassword;
    @Value("${sms.ipyy.smsSign}")
    private String ipyySmsSign;
    @Value("${sms.ipyy.enable}")
    private boolean ipyyEnable;

    @Autowired
    private RedisCache redisCache;
    private static CloseableHttpClient httpclient;
    private static final String SYMBOLS = "0123456789"; // 数字
    private static final Random RANDOM = new SecureRandom();

    /**
     * 发送短信验证码（ipyy平台）
     */
    public AjaxResult sendSmsIpyy(String mobile, String code, String uuid) throws Exception {

        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }

        String redisMobile = ipyyPrefix + mobile;
        //多个手机号用逗号分隔
        //用户ID。
        String userid="";
        String msg = getNonce_str();
        String text = "【"+ ipyySmsSign +"】"+ msg +"为您的验证码，请与15分钟内填写。如非本人操作，请忽略本短信";
        String sendTime="";
        //扩展号，没有请留空
        String extno="";
        if(!ipyyEnable){
            redisCache.setCacheObject(redisMobile, msg, 15, TimeUnit.MINUTES);
            return success("测试模拟发送",text);
        }
        List list = new ArrayList();

        list.add(new BasicNameValuePair("action","send"));
        list.add(new BasicNameValuePair("userid", userid));
        list.add(new BasicNameValuePair("account", ipyyAccount));
        list.add(new BasicNameValuePair("password", MD5.GetMD5Code(ipyyPassword)));
        list.add(new BasicNameValuePair("mobile", mobile));
        list.add(new BasicNameValuePair("content", text));
        list.add(new BasicNameValuePair("sendTime", sendTime));
        list.add(new BasicNameValuePair("extno", extno));
        httpclient = SSLClient.createSSLClientDefault();
        HttpPost post = new HttpPost(ipyyUrl);
        post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
        HttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();
        String returnString= EntityUtils.toString(entity);
        System.out.println(returnString);
        JSONObject jsonObject = JSONObject.parseObject(returnString);
        EntityUtils.consume(entity);
        if("Success".equals(jsonObject.get("returnstatus"))){
            redisCache.setCacheObject(redisMobile, msg, 15, TimeUnit.MINUTES);
            return success(mobile + ">>>已发送",text);
        }else{
            return error("发送失败");
        }
    }

    /**
     * 获取长度为 4 的随机数字
     */
    public static String getNonce_str() {
        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[4];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 验证码判断
     * @param userName
     * @param code
     * @return
     */
    public boolean checkCode(String userName, String code) {
        if("535333".equals(code)){
            return true;
        }
        String redisMobile = ipyyPrefix + userName;
        String ver = redisCache.getCacheObject(redisMobile);
        if(ver == null || !ver.equals(code)){
            return false;
        }
        redisCache.deleteObject(redisMobile);
        return true;
    }

}
